package cn.lizemin.fakedata.project.elementUi.controller;

import cn.lizemin.fakedata.common.PageData;
import cn.lizemin.fakedata.common.RespBean;
import cn.lizemin.fakedata.converter.ElementUserConverter;
import cn.lizemin.fakedata.project.elementUi.DTO.ElementUserDTO;
import cn.lizemin.fakedata.project.elementUi.VO.ElementUserVO;
import cn.lizemin.fakedata.project.elementUi.entity.ElementUser;
import cn.lizemin.fakedata.project.elementUi.service.IElementUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 学习element ui时需要用到的用户表 前端控制器
 * </p>
 *
 * @author lizemin
 * @since 2024-01-18
 */
@RestController
@RequestMapping("/elementUi/elementUser")
public class ElementUserController {

    @Autowired
    private IElementUserService elementUserService;

    @PostMapping
    public RespBean addOrUpdateUser(ElementUserDTO user) {
        if (Objects.isNull(user.getId())) {
            elementUserService.addUser(user);
            return RespBean.success().message("添加成功");
        } else {
            elementUserService.updateUser(user);
            return RespBean.success().message("修改成功");
        }
    }

    @GetMapping
    public RespBean listUser() {
        List<ElementUser> users = elementUserService.list();
        List<ElementUserVO> userVos = ElementUserConverter.toElementUserVos(users);
        return RespBean.success(userVos);
    }

    @GetMapping("/pageListUser")
    public RespBean pageListUser(@RequestParam(value = "currentPage", defaultValue = "1") Long currentPage,
                                 @RequestParam(value = "pageSize", defaultValue = "5") Long pageSize) {
        PageDTO<ElementUser> userPageDTO = elementUserService.pageListUser(currentPage, pageSize);
        List<ElementUser> users = userPageDTO.getRecords();
        List<ElementUserVO> userVos = ElementUserConverter.toElementUserVos(users);
        PageData<ElementUserVO> pageData = new PageData<>();
        pageData.setData(userVos);
        pageData.setTotal(userPageDTO.getTotal());
        return RespBean.success(pageData);
    }

    @DeleteMapping
    public RespBean deleteUser(Integer id) {
        elementUserService.deleteUser(id);
        return RespBean.success();
    }


}
